const gulp = require("gulp");
const babel = require("gulp-babel");
const gulpHtml = require("gulp-htmlmin");
const uglify = require("gulp-uglify");
const css = require("gulp-clean-css");
const removeDebug = require("gulp-strip-debug");
const del = require("del");
const image = require("gulp-imagemin");

//清空dist文件夹
gulp.task("clearAll", function () {
  return del("build/");
});
//添加html压缩任务
gulp.task("html", (done) => {
  gulp
    .src(["./source/**/*.html", "./source/*.html"])
    .pipe(
      gulpHtml({
        //删除空格
        collapseWhitespace: true,
        //删除注释
        removeComments: true,
      })
    )
    .pipe(gulp.dest("build/"));
  done();
});

//js文件打包
gulp.task("js", (done) => {
  gulp
    .src([
      "./source/**/*.js",
      "./source/*.js",
      "!./source/**/Plug-ins/**/*",
      // "!./source/**/*.min.js",
      // "!./source/*.min.js",
      // "!jweixin-1.6.0.js",
      // "!jweixin-1.2.0.js",
    ])
    .pipe(babel()) //ES6转换为ES5
    .pipe(removeDebug()) //删除debug和console.log
    .pipe(
      uglify({
        mangle: false, //类型：Boolean 默认：true， 是否修改变量名
        compress: false, //类型：Boolean 默认：true， 是否完全压缩
      })
    ) //js代码压缩
    .pipe(gulp.dest("build/"));
  done();
});

// css文件打包
gulp.task("cssMin", (done) => {
  gulp
    .src(["./source/**/*.css", "./source/*.css"])
    .pipe(css({ compatibility: "ie8" })) //压缩css文件
    .pipe(gulp.dest("build/"));
  done();
});
//压缩图片
gulp.task("imagemin", (done) => {
  gulp
    .src(["./source/**/**/*.{jpg,png,svg}", "./source/**/*.{jpg,png,svg}"])
    .pipe(image())
    .pipe(gulp.dest("build/"));
  done();
});

//copy
gulp.task("copy", (done) => {
  gulp.src("./source/**/Plug-ins/**/*").pipe(image()).pipe(gulp.dest("build/"));
  done();
});

// 开启一个任务
gulp.task(
  "default",
  gulp.series("clearAll", "html", "js", "cssMin", "imagemin", "copy")
);
gulp.task("watch", () => {
  gulp.watch("./source/**/*.*", gulp.series("default"));
});
